package org.visionlibrary.image.filters.thresholding;

import javax.media.jai.TiledImage;

import org.visionlibrary.image.acquisition.ImageFactory;
import org.visionlibrary.image.model.AbstractFilter;


public class ColorThresholding extends AbstractFilter {
	int[] thre = null;
	int[] back = null;
	
	public int[] getThreshold() {
		return thre;
	}

	public void setThreshold(int[] hsv) {
		this.thre = hsv;
	}

	public int[] getBackground() {
		return back;
	}

	public void setBackground(int[] hsv) {
		this.back = hsv;
	}

	@Override
	public TiledImage applyFilter(TiledImage src, TiledImage dest) {
		if (null == src)
			throw new NullPointerException("Source image is null.");

		if (null == dest)
			dest = (new ImageFactory()).createCompatibleImage(src);
		
		int maxX = src.getWidth();
		int maxY = src.getHeight();

		for (int x = 0; x < maxX; x++)
			for (int y = 0; y < maxY; y++) {
				double[] rgb = new double[src.getNumBands()];
				for (int ch = 0; ch < src.getNumBands(); ch++) {
					rgb[ch] = src.getSample(x, y, ch);
				}
				if(rgb[0] == thre[0] && rgb[1] == thre[1] && rgb[2] == thre[2]) {
					rgb[0] = thre[0]; 
					rgb[1] = thre[1];
					rgb[2] = thre[2];
				} else {
					rgb[0] = back[0]; 
					rgb[1] = back[1];
					rgb[2] = back[2];
				}
				
				for (int i = 0; i < rgb.length; i++) {
					dest.setSample(x, y, i, rgb[i]);
				}
			}

		return dest;
	}
}
